﻿using ComClassLibrary;
using LogLib;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;

namespace SelectKeyBoard
{
    public class MenuConfig
    {
        private DataSet _dataSetSrc = new DataSet();

        /// <summary>
        /// 按钮高度
        /// </summary>
        public int ButtonHeight { private set; get; } = 23;   
        
        /// <summary>
        /// 按钮宽度
        /// </summary>
        public int ButtonWidth { private set; get; } = 64;

        /// <summary>
        /// 按钮排布布局的水平间隔
        /// </summary>
        public int ButtonHorDistance { private set; get; } = 5; 

        /// <summary>
        ///  按钮排布布局的垂直间隔
        /// </summary>
        public int ButtonVerDistance { private set; get; } = 5;

        /// <summary>
        ///  按钮到画布右侧边界的距离
        /// </summary>
        public int ButtonHorOffSet { private set; get; } = 10;
        
        /// <summary>
        /// 按钮到画布底部边界的距离
        /// </summary>      
        public int ButtonVerOffSet { private set; get; } = 10;
       
        /// <summary>
        /// 按钮文字大小
        /// </summary>
        public int ButtonFontSize { private set; get; } = 16;
      
        /// <summary>
        /// 标题文字大小
        /// </summary>
        public int TitleFontSize { private set; get; } = 24;   
        
        /// <summary>
        /// 选择级数
        /// </summary>
        public int TotalLevel { private set; get; }  = 0;

        /// <summary>
        /// 当前级数
        /// </summary>
        public int CurrentLevel { set; get; } = 1;

        public List<XNode> Nodes { private set; get; } = new List<XNode>();

        public string TitleValue { private set; get; } = "";   

        public string ReadTitle(string path)
        {
            StreamReader sr = new StreamReader(path, Encoding.UTF8);
            string ret = "";
            string line = "";
            while ((line = sr.ReadLine()) != null)
            {
                ret += line;
            }
            return ret;
        }

        public void ReadIniConfig(string fileName)
        {
            //string str = IniFile.IniValue("setting", "Title", "", fileName);;
            string titleValue = IniFile.IniValue("setting", "Title", "", fileName);
            string titleFileName = string.Format("{0}\\{1}", Path.GetDirectoryName(fileName), titleValue);
            if (File.Exists(titleFileName))
            {
                TitleValue = ReadTitle(titleFileName);
            }
            else
            {
                TitleValue = titleValue;
            }
            TitleFontSize = int.Parse(IniFile.IniValue("setting", "TitleFontSize", "24", fileName));
            ButtonHeight = int.Parse(IniFile.IniValue("setting", "ButtonHeight", "23", fileName));
            ButtonWidth = int.Parse(IniFile.IniValue("setting", "ButtonWidtht", "64", fileName));
            ButtonHorDistance = int.Parse(IniFile.IniValue("setting", "ButtonHorDistance", "5", fileName));
            ButtonVerDistance = int.Parse(IniFile.IniValue("setting", "ButtonVerDistance", "5", fileName));
            ButtonHorOffSet = int.Parse(IniFile.IniValue("setting", "ButtonHorOffSet", "0", fileName));
            ButtonVerOffSet = int.Parse(IniFile.IniValue("setting", "ButtonVerOffSet", "0", fileName));
            ButtonFontSize = int.Parse(IniFile.IniValue("setting", "ButtonFontSize", "10", fileName));
        }

        public void Reset()
        {
            TotalLevel = 0;
            CurrentLevel = 1;
            Nodes.Clear();
            _dataSetSrc.Clear();

        }

        public void TryParse(string xmlFileName)
        {
            _dataSetSrc = new DataSet();
            _dataSetSrc.ReadXml(xmlFileName);
            TotalLevel = _dataSetSrc.Tables.Count;
            if (TotalLevel < 2)
            {
                return;
            }
            DataTable dt = _dataSetSrc.Tables[1];
            var drs = dt.Rows;
            string idColName = $"{dt.TableName}_Id";
            bool containsCol = dt.Columns.Contains(idColName);
            for (int j = 0; j < drs.Count; j++)
            {
                DataRow dr = drs[j];
                XNode node = new XNode();
                if(containsCol)
                {
                    node.Id = (int)dr[idColName];
                }
                else
                {
                    node.Id = j;
                }
                node.IndexName = dt.TableName;
                node.Key = dr["key"].ToString();
                node.Value = dr["value"].ToString();
                if(dt.Columns.Contains("code"))
                {
                    node.Code = dr["code"].ToString();
                }
                node.Level = 1;
                Nodes.Add(node);
                if (node.Level >= TotalLevel - 1)
                {
                    node.IsLeaf = true;
                    continue;
                }
                SelectChild(node);
            }
            Log.Write(Nodes.Count.ToString());
        }

        private void SelectChild(XNode node)
        {         
            int level = node.Level + 1;
            string tableName = $"level{level}";
            DataTable dt = _dataSetSrc.Tables[tableName];
            string nodeIdName = $"{node.IndexName}_Id";           
            var drs = dt.Select($"{nodeIdName}={node.Id}");
            if(drs.Length == 0)
            {
                node.IsLeaf = true;
                return;
            }
            string idColName = $"{dt.TableName}_Id";
            bool is_leaf = dt.Columns.Contains(idColName);
            for (int j = 0; j < drs.Length; j++)
            {
                DataRow dr = drs[j];
                XNode child = new XNode();
                if (is_leaf)
                {
                    child.Id = (int)dr[idColName];
                }
                else
                {
                    child.Id = j;
                }
                child.IndexName = dt.TableName;
                child.Key = dr["key"].ToString();
                child.Value = dr["value"].ToString();
                if (dt.Columns.Contains("code"))
                {
                    node.Code = dr["code"].ToString();
                }
                child.Level = level;
                child.Parent = node;           
                if (child.Level >= TotalLevel - 1)
                {
                    child.IsLeaf = true;
                }
                node.ChildNodes.Add(child);
                Nodes.Add(child);
                if (!child.IsLeaf)
                {
                    SelectChild(child);
                }              
            }
        }

    }
}
